/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tesam.gedeon.controller;

import com.tesam.gedeon.entity.Provider;
import com.tesam.gedeon.service.ProviderService;
import com.tesam.gedeon.service.SystemUserService;
import com.tesam.gedeon.util.Util;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author joelpacheco
 */
@Controller
public class ProviderController {

    @Autowired
    ProviderService providerService;
    @Autowired
    private SystemUserController system;
    @Autowired
    private SystemUserService systemUserService;

    @RequestMapping(value = "/provider/index", method = RequestMethod.GET)
    public ModelAndView rolIndex(HttpServletRequest request, HttpServletResponse response) {

        // RequestContextUtils.getLocaleResolver(request).setLocale(request, response, new Locale(request.getParameter("language")));
        ModelAndView mv = new ModelAndView("/provider/index");
        String module = request.getParameter("module");
        if (!Util.isNullOrEmpty(module)) {
            request.getSession().setAttribute("module", module);
        }

        System.out.println("Ingreso en el indice");
        //request.getSession().getAttribute("moduleId",request.getParameter("module"));
        system.loadDataSystem(mv, request);
        return mv;
    }

    @RequestMapping(value = "/provider/new", method = RequestMethod.GET)
    public ModelAndView newProvider(HttpServletRequest request) {

        Provider provider = new Provider();
        ModelAndView mv = new ModelAndView("/provider/new");
        //System.out.println("Session" + request.getSession().getAttribute("module"));
        system.loadDataSystem(mv, request);
        request.getSession().setAttribute("tokenProvider", 1);
        mv.addObject("provider", provider);
        return mv;
    }

    @RequestMapping(value = "/provider/save", method = RequestMethod.POST)
    public ModelAndView saveProvider(@ModelAttribute("provider") Provider provider, SessionStatus status, HttpServletRequest request) {

        String message = null;

        ModelAndView mv = new ModelAndView("redirect:/provider/index");

        String token = (request.getSession().getAttribute("tokenProvider") == null) ? "" : request.getSession().getAttribute("tokenProvider").toString();

        if (token == null || token.isEmpty()) {

            return mv;
        } else {

            provider.setCreatedBy(1);
            if (providerService.save(provider) > 0) {

                request.getSession().removeAttribute("tokenProvider");

                mv = new ModelAndView("/provider/index");

                message = "<div class=\"alert alert-block alert-success fade in\">"
                        + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                        + "<strong>Éxito! </strong>"
                        + " Proveedor " + provider.getName() + " registrado correctamente"
                        + "</div>";

                mv.addObject("message", message);

            } else {

                message = "<div class=\"alert alert-block alert-error fade in\">"
                        + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                        + "<strong>Fallo! </strong>"
                        + " Ocurrio un error al tratar de registrar proveedor" + provider.getName() + " en el servidor"
                        + "</div>";

                mv.addObject("message", message);
            }
        }
        system.loadDataSystem(mv, request);
        return mv;
    }

    @RequestMapping(value = "/provider/edit", method = RequestMethod.GET)
    public ModelAndView editProvider(HttpServletRequest request) {

        ModelAndView mv = null;
        int providerId = Integer.parseInt(request.getParameter("id"));
        request.getSession().setAttribute("tokenProvider", 1);
        Provider provider;
        provider = providerService.getById(providerId);
        mv = new ModelAndView("/provider/edit");
        mv.addObject("provider", provider);
        system.loadDataSystem(mv, request);
        return mv;
    }

    @RequestMapping(value = "/provider/edit", method = RequestMethod.POST)
    public ModelAndView editProvider(@ModelAttribute("provider") Provider provider, SessionStatus status, HttpServletRequest request) {

        String message = null;

        ModelAndView mv = new ModelAndView("redirect:/provider/index");

        String token = (request.getSession().getAttribute("tokenProvider") == null) ? "" : request.getSession().getAttribute("tokenProvider").toString();

        if (token == null || token.isEmpty()) {

            return mv;
        } else {

            provider.setModifiedBy(1);

            if (providerService.update(provider) > 0) {

                request.getSession().removeAttribute("tokenProvider");

                mv = new ModelAndView("/provider/index");

                message = "<div class=\"alert alert-block alert-success fade in\">"
                        + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                        + "<strong>Éxito! </strong>"
                        + " Proveedor " + provider.getName() + " actualizado correctamente"
                        + "</div>";

                mv.addObject("message", message);

            } else {

                message = "<div class=\"alert alert-block alert-error fade in\">"
                        + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                        + "<strong>Fallo! </strong>"
                        + " Ocurrio un error al tratar de actualizar proveedor " + provider.getName() + " en el servidor"
                        + "</div>";

                mv.addObject("message", message);
            }
        }
        system.loadDataSystem(mv, request);
        return mv;
    }

    @RequestMapping(value = "/provider/delete", method = RequestMethod.GET)
    public ModelAndView deleteProvider(HttpServletRequest request, SessionStatus status) {
        System.out.println("Entro");
        String message = null;
        ModelAndView mv = new ModelAndView("redirect:/provider/index");

        int rolId = Integer.parseInt(request.getParameter("id"));

        if (rolId > 0) {

            Provider provider = providerService.getById(rolId);

            if (provider != null) {

                provider.setModifiedBy(1);

                mv = new ModelAndView("/provider/index");

                if (providerService.delete(provider) > 0) {

                    status.setComplete();
                    message = "<div class=\"alert alert-block alert-success fade in\">"
                            + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                            + "<strong>Éxito! </strong>"
                            + " Proveedor " + provider.getName() + " eliminado correctamente"
                            + "</div>";

                    mv.addObject("message", message);

                } else {
                    message = "<div class=\"alert alert-block alert-error fade in\">"
                            + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                            + "<strong>Fallo! </strong>"
                            + " Ocurrio un error al tratar de eliminar proveedor " + provider.getName() + " en el servidor"
                            + "</div>";

                    mv.addObject("message", message);
                }
            }
        }
        system.loadDataSystem(mv, request);
        return mv;
    }

    @RequestMapping(value = "/provider/view", method = RequestMethod.GET)
    public ModelAndView viewProvider(HttpServletRequest request) {

        ModelAndView mv = null;
        int providerId = Integer.parseInt(request.getParameter("id"));
        request.getSession().setAttribute("tokenProvider", 1);
        Provider provider = providerService.getById(providerId);

        provider.setSystemUser(systemUserService.getById(provider.getCreatedBy()));

        mv = new ModelAndView("/provider/view");
        mv.addObject("provider", provider);
        system.loadDataSystem(mv, request);
        return mv;
    }

    @RequestMapping(value = "/provider/ajax", method = RequestMethod.POST, produces = "application/json")
    public @ResponseBody
    String doAjaxPost(HttpServletRequest request) {


        List<Provider> listaDeRoles = null;
        int cantidadRegistros = 0;

        String[] columns = {"id", "code", "name", "datecreated"};

        String startLimit = request.getParameter("iDisplayStart");
        String endLimit = request.getParameter("iDisplayLength");
        String dataToSort = columns[Integer.valueOf(request.getParameter("iSortCol_0"))];
        String directionOfOrder = request.getParameter("sSortDir_0");
        String textSearch = request.getParameter("sSearch").toUpperCase();
        String moduleId = request.getSession().getAttribute("module").toString();

        int _moduleId = 0;

        if (!moduleId.isEmpty()) {
            _moduleId = Integer.parseInt(moduleId);
        }

        int _startLimit = 0;
        int _endLimit = 0;

        if (startLimit != null && !startLimit.equals("0")) {

            if (!startLimit.trim().isEmpty()) {
                _startLimit = Integer.valueOf(startLimit);
            }
        }

        if (endLimit != null && !endLimit.equals("0")) {
            if (!endLimit.trim().isEmpty()) {
                _endLimit = Integer.valueOf(endLimit);
            }
        }

        if (textSearch != null) {
            if (!textSearch.trim().isEmpty()) {
                textSearch = textSearch.trim();
                Provider provider = new Provider();
                provider.setName(textSearch);
                listaDeRoles = providerService.searchByName(provider, _startLimit,
                        (_endLimit));
                cantidadRegistros = providerService.getCountSearchByName(provider);
                return providerService.getJsonDataFromArrayList(listaDeRoles, cantidadRegistros, _moduleId);

            }
        }

        listaDeRoles = providerService.getAllByLimit(_startLimit,
                (_endLimit), dataToSort, directionOfOrder);

        cantidadRegistros = providerService.getCountTotal();

        return providerService.getJsonDataFromArrayList(listaDeRoles, cantidadRegistros, _moduleId);
    }
}
